#!/bin/sh
## A script to set up a ssh tunnel for a "local" connection to the sdf ircd and be run with cron_key.sh

# Run in crontab with:
# */10 * * * * /home/demure/projects/personal/scripts/sdf_tun_ssh.sh

LOCAL_PORT="2003"
SERVER="ma.sdf.org"
IRC_HOST="irc.sdf.org"
IRC_PORT="6697"
## Set command as a var to save time
SSH_COMMAND="ssh -f -N -L ${LOCAL_PORT}:${IRC_HOST}:${IRC_PORT} ${SERVER}"
## Check how many ssh sessions are running on the port
CHECK="$(pgrep -f "${SSH_COMMAND}" | wc -l)"

## If no sessions, start one; if more than one, kill them and start a new one.
if [ "${CHECK}" -eq "0" ]; then
    ${SSH_COMMAND}
  else
    if [ "${CHECK}" -gt "1" ]; then
        pkill -f "${SSH_COMMAND}"
        ${SSH_COMMAND}
    fi
fi
